package cn.tedu.luban.settle.main.service;

import cn.tedu.luban.account.api.AccountApi;
import cn.tedu.luban.account.protocol.param.AccountPayParam;
import cn.tedu.luban.order.protocol.dto.OrderMessageDTO;
import cn.tedu.luban.settle.main.converter.SettleConverter;
import cn.tedu.luban.settle.main.repository.SettleRepository;
import cn.tedu.luban.settle.main.service.MessageService;
import cn.tedu.luban.settle.protocol.param.SettleBillParam;
import com.tedu.inn.protocol.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SettleSevice {

    @Autowired
    private SettleRepository settleRepository;

    @Autowired
    private SettleConverter settleConverter;

    @Autowired
    private MessageService messageService;

    @Autowired
    private AccountApi accountApi;

    @Transactional(rollbackFor = Exception.class)
    public void settle(OrderMessageDTO orderMessageDTO) throws BusinessException {
        //1.利用订单编号，查询当前账单是否存在
        String orderNo = orderMessageDTO.getOrderNo();
        Long total = settleRepository.countSettleBillByOrderNo(orderNo);
        //2.结果判断，如果没有账单，则生成账单，如果有账单，则结束
        if (total==0){
            List<SettleBillParam> settleBillParams = settleConverter.dto2params(orderMessageDTO);
            settleRepository.batchSave(settleBillParams);
            // 远程调用打款，调用account
            AccountPayParam accountPayParam = new AccountPayParam();
            accountPayParam.setUserId(orderMessageDTO.getUserId());
            accountPayParam.setOrderNo(orderNo);
            accountPayParam.setTotalAmount(settleBillParams.get(0).getTotalAmount());
            accountApi.mockPayment(accountPayParam);

            //4.发送消息，通知订单消费者，修改订单最终完成状态，告诉订单服务哪张订单可以完成了
            messageService.sendSettledMessage(orderNo);
        }else {
            throw new BusinessException("2000","该订单重复创建账单");

        }
    }

}
